#!/usr/bin/env python
# encoding: utf-8

from PyQt5.QtWidgets import *
from PyQt5.QtGui import *
from PyQt5.QtCore import *

import os
import configparser
import binascii
from Help import Help
from Help import WATER_CMD
help = Help()

from ui.envMeasure import Ui_Dialog
class EnvMeasureWidget(QDialog,Ui_Dialog):
    signal_msg = pyqtSignal(str,str)
    def __init__(self,parent=None, serial=None):
        super(QDialog, self).__init__(parent)
        self.setupUi(self)
        self.setWindowIcon(QIcon(':icons/images_rc/box.png'))
        self.setWindowTitle("本底测量")
        # 配置文件读取
        # self.readConfig()
        self.period = 200
        # 串口模块
        self.serial = serial
        self.pushButton_start.clicked.connect(self.env_start)
        self.progressBar.setRange(0, 100)
        self.progressBar.setValue(0)
        self.signal_msg.connect(self.MessageBox)

    def readConfig(self):
        self.configfile = os.getcwd()+'/conf/base.ini'
        config = configparser.ConfigParser()
        config.read(self.configfile)
        self.period = int(config['base']['period'])

    def start(self):
        cmd = WATER_CMD['数据读取']
        cmd[4] = '08'
        self.cmd_send(cmd)
        pass

    def env_start(self):
        '''开始本底测量'''
        self.cmd_send(WATER_CMD['本底测量'])
        # self.env_step = 0  # 本底测量步骤
        # self.env_write_ok = True
        # self.env_measure_t1 = []
        # self.env_measure_t2 = []
        # self.env_measure_flag = False
        # self.env_measure_cnt = 0
        # self.timer_env = QTimer()
        # self.timer_env.timeout.connect(self.env_timer)
        # self.timer_env.start(1000)
        # self.dataTab.clear_data()

    def env_timer(self):
        if self.env_write_ok:
            if self.env_step == 0:  # 第1步打开本底测量
                self.cmd_send(WATER_CMD['本底测量'])
                self.env_write_ok = False
            if self.env_step == 1:  # 第2步打开测量
                self.cmd_send(WATER_CMD['开始测量'])
                self.env_write_ok = False
            if self.env_step == 2:  # 第3步关闭测量
                self.cmd_send(WATER_CMD['停止测量'])
                self.env_write_ok = False
            if self.env_step == 3:
                self.timer_env.stop()

    def env_measure(self, data):
        '''调试测量数据'''
        t1 = 0
        t2 = 0
        if data[:2] == 'FF':
            t1 = int(data[:8], 16) - int('FFFFFFFF', 16) - 1
        else:
            t1 = int(data[:8], 16)
        if data[-8:-6] == 'FF':
            t2 = int(data[-8:], 16) - int('FFFFFFFF', 16) - 1
        else:
            t2 = int(data[-8:], 16)

        if self.repeat_measure_flag:
            self.repeatMeasureDlg.table_add_data(x=self.real_x, y=self.real_y, z=self.real_z, t1=t1, t2=t2)
            return

        if self.env_measure_flag:
            self.dataTab.add_data(x=self.real_x, y=self.real_y, z=self.real_z, t1=t1, t2=t2)
            self.env_measure_cnt += 1
            self.env_measure_t1.append(abs(t1))
            self.env_measure_t2.append(abs(t2))
            cnt = ENV_COUNT
            # self.signalEnv.emit(float('%0.1f'%(self.env_measure_cnt*100/int(cnt))))
            self.progressBar_env.setValue(float('%0.1f' % (self.env_measure_cnt * 100 / int(cnt))))
            if self.env_measure_cnt > cnt:
                self.env_measure_flag = False
                self.env_measure_cnt = 0
                self.env_write_ok = True
                self.env_step += 1
                ave_t1 = sum(self.env_measure_t1) / len(self.env_measure_t1)
                ave_t2 = sum(self.env_measure_t2) / len(self.env_measure_t2)
                # self.env_bar.close()
                if ave_t1 < ENV_THRESHOLD and ave_t2 < ENV_THRESHOLD:
                    # self.qta_env_status.setStyleSheet('color:green;')
                    QMessageBox.information(self, '漏射线测量', '测量合格', QMessageBox.Yes)
                else:
                    # self.qta_env_status.setStyleSheet('color:red;')
                    QMessageBox.information(self, '漏射线测量', '测量不合格', QMessageBox.Yes)
                self.cmd_send(WATER_CMD['停止测量'])
        else:
            self.dataTab.add_data(x=self.real_x, y=self.real_y, z=self.real_z, t1=t1, t2=t2)
            self.measureX += 1
            self.measureList.append([self.measureX, t1, t2])
            data = self.measureList
            self.signalTunnel.emit([d[0] for d in data], [d[1] for d in data], [d[2] for d in data], )

    def serial_deal(self, cmd, data):
        """ 线程接收信息处理，提示消息需要用信号发送的方式"""
        if cmd == '72':  # 本底测量
            t = int(data, 16) * self.period / 1000
            t1 = float('%0.1f' % (100 - t * 100 / 30))
            print(t1)
            self.progressBar.setValue(t1)
            # if DEBUG:
                # print('本底测量剩余时间:%s' % t)
            if t == 0:
                self.signal_msg.emit("提示","测量完成")
                self.progressBar.setValue(0)
                self.close()

                # self.env_measure_flag = True
                # self.env_write_ok = True
                # self.env_step += 1

    def cmd_send(self, cmd_list):
        cmd = help.cmd_build(cmd_list)
        if self.serial.isOpen():
            data = binascii.unhexlify(cmd)
            print('发送命令：', ' '.join([cmd[i * 2:i * 2 + 2] for i in range(0, int(len(cmd) / 2))]))
            self.serial.write(data)
        else:
            QMessageBox.information(self, '通信提示', '通信异常,请检查通信接口', QMessageBox.Yes)

    def MessageBox(self,title='',msg=''):
        QMessageBox.information(self,title,msg,QMessageBox.Yes)

